<?php

namespace App\Http\Controllers\Api\Room;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Rooms\RoomsGoodsBuy;
use Illuminate\Http\Request;

class ShoppingController extends Controller
{
    private $buy;

    public function __construct()
    {
        $this->buy = new Context(new RoomsGoodsBuy);
    }

    public function index(Request $request)
    {
        $goods = $this->buy->display($request->limit,function($query) use($request){
            $query->with('member');
            if($request->keyword)
            {
                $query->whereHas('member',function($query){
                $query->where('nickname','like','%'.request()->keyword.'%')->orWhere('mobile',request()->keyword);
                });
            }
            if($request->sale_type)
            {
               $query->where('sale_type',$request->sale_type);
            }
            if($request->status)
            {
               $query->where('status',$request->status);
            }
            if(isset($request->time[0]) && !empty($request->time[0])){
                $query->whereBetween('created_at',$request->time);
            }
            $query->whereIn('status',[2,3,6]);
            return $query;
        });
        return $this->success($goods);
    }


    public function show($id)
    {
        $buy = $this->buy->find($id);
        return $this->success([
            'buy' => $buy,
            'room_goods' => $buy->room_goods,
            'member' => $buy->member
        ]);
    }


    public function update(Request $request,$id){
        if(is_null($id) && empty($request->code))
        {
            return $this->error('操作失败');
        }
        $res = $this->buy->find($id);
        if($res->consignee && $res->phone && $res->area && $res->area)
        {
            if($res->status == 6)
            {
                return $this->error('该商品已经发货了，请不要重复操作');
            }
            $res->status = 6;
            $res->action_at = now();
            $res->shopning_code = $request->code;
            $res->save();
            return $this->success(['message' => '操作成功']);
        }
        return $this->error('该用户没有完整的地址信息不能发货');
    }
}
